package com.ohuang.jiaxiaotong.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.bunny.android.library.LoadDataLayout;
import com.ohuang.jiaxiaotong.Activity.UploadFileActivity;
import com.ohuang.jiaxiaotong.Adapter.DataFileRvAdapter;
import com.ohuang.jiaxiaotong.Adapter.DataFileRvAdapter2;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.Util.Sys;
import com.ohuang.jiaxiaotong.base.LazyFragment;
import com.ohuang.jiaxiaotong.entity.ClassUrl;
import com.ohuang.jiaxiaotong.entity.EventMsg;
import com.ohuang.jiaxiaotong.entity.User;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import com.ohuang.jiaxiaotong.R;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;

public class DataFile2Fragment extends LazyFragment {
    private static String TAG = "DataFile2Fragment";
    private String className;
    private RecyclerView recyclerView;
    private DataFileRvAdapter2 dataFileRvAdapter2;
    private ArrayList<ClassUrl> mData;
    private User user;
    private LoadDataLayout loadDataLayout;


    public DataFile2Fragment() {
        // Required empty public constructor
    }

    public DataFile2Fragment(String className) {
        this.className = className;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    protected void initView(View root) {
        initView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_data_file2;
    }

    private void initView() {
        recyclerView = view.findViewById(R.id.rv_dataFile2);
        loadDataLayout = view.findViewById(R.id.loadData_dataFile2);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(null);
        loadDataLayout.showLoading("正在努力加载中", new LoadDataLayout.SetImgCallBack() {
            @Override
            public void setImg(ImageView img) {
                Glide.with(getActivity())
                        .load(R.drawable.gif_loading)
                        .into(img);
            }
        });//显示 load布局 状态正在加载

    }

    @Override
    public void startLoad() {
        Log.d(TAG, "startLoad: ");
        if (user != null) {
            HttpGetClassUrl();
        }
    }

    //true为收藏 false为取消收藏
    private void httpCollectClassUrl(String id, boolean isCheck) {
        String aa;
        if (isCheck) {
            aa = "user/addCollect";
        } else {
            aa = "user/deleteCollect";
        }
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("dataId", id)
                .add("username", user.getUsername())
                .build();


        final Request request = new Request.Builder()
                .url(MyHttpURL.mainUrl + aa)
                .post(formBody)
                .build();

        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {

                ResponseBody body = response.body();
                if (body != null) {
                    String code = body.string();
                    if ("success".equals(code)) {

                    }
                    body.close();
                }
            }
        });
    }


    private void HttpGetClassUrl() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("className", className);

        service.GetClassUrl(map).enqueue(new Callback<ArrayList<ClassUrl>>() {
            @Override
            public void onResponse(Call<ArrayList<ClassUrl>> call, Response<ArrayList<ClassUrl>> response) {
                mData = response.body();
                if (mData.size() == 0) {
                    loadDataLayout.showEmpty();
                } else {
                    loadDataLayout.showSuccess();
                }
                dataFileRvAdapter2 = new DataFileRvAdapter2(getActivity(), mData);
                dataFileRvAdapter2.setOnItemClickListener(new DataFileRvAdapter2.OnItemClickListener() {
                    @Override
                    public void CheckBoxOnCheckedChanged(CheckBox checkBox, int position, CompoundButton buttonView, boolean isChecked) {

                        if (isChecked) {
                            Toast.makeText(getContext(), "已收藏", Toast.LENGTH_SHORT).show();
                            httpCollectClassUrl(mData.get(position).getId() + "", true);
                        } else {
                            Toast.makeText(getContext(), "取消收藏", Toast.LENGTH_SHORT).show();
                            httpCollectClassUrl(mData.get(position).getId() + "", false);
                        }
                    }

                });
                recyclerView.setAdapter(dataFileRvAdapter2);

            }

            @Override
            public void onFailure(Call<ArrayList<ClassUrl>> call, Throwable t) {
                loadDataLayout.showError();
            }
        });
    }

    interface GithubService {
        //https://api.github.com/repos/{owner}/{repo}/contributors
        @POST("user/findAllData")
        Call<ArrayList<ClassUrl>> GetClassUrl(@QueryMap HashMap<String, String> deviceInfo);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetUserEventBus(User user) {
        this.user = user;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
